from pylons import tmpl_context as c
from pylons import config
from pylons.controllers.util import redirect

from harstorage.lib.base import BaseController, render
from harstorage.lib.MongoHandler import MongoDB
from harstorage.lib.HAR import HAR

import datetime

MIGRATION_STATUS = "ok_1"

class MigrationController(BaseController):

    def __before__(self):
        """Define version of static content"""

        c.rev = config["app_conf"]["static_version"]

    def status(self):
        return render("/migration.html")

    def migration(self):



        def get_series_id(label, url):
            series_doc = MongoDB().series.find_one({"url": url, "label": label})
            if series_doc:
                return None
            else:
                series_doc = {"url": url,
                              "label": label,
                              "title": label + " (" + url + ")",
                              "last_run": datetime.datetime.now()}
                MongoDB().series.insert(series_doc)
                return series_doc["_id"]


        print "Starting migration..."

        # MongoDB handler
        mdb_handler = MongoDB()
        if hasattr(c, "message"):
            return render("/error.html")

        urls = set()
        cnt = 0

        for document in mdb_handler.collection.find(fields=["_id", "url", "label"]):
            id = document["_id"]
            urls.add((document["label"], document["url"]))

            cnt += 1

            if cnt % 1000 == 0:
                print cnt, "docs updated"

        migration_handler = MongoDB(collection = "migration")
        migration_handler.collection.insert({"status": MIGRATION_STATUS})

        for label, url in urls:
            print "Creating series ", label, url
            series_id = get_series_id(label, url)
            if series_id:
                mdb_handler.collection.update({"label": label, "url": url}, {"$set": {"series": series_id}}, multi = True)

        print "dropping indices (for rebuilding)..."
        mdb_handler.collection.drop_indexes()

        redirect("/")
